package com.mayikt.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTemplateUtils {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void setObject(String key, Object value) {
        setObject(key, value, null);
    }

    public void setObject(String key, Object value, Long timeout) {
        redisTemplate.opsForValue().set(key, value);
        if(timeout != null) {
            redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
        }
    }

    public Object getObject(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void deleteObject(String key) {
        redisTemplate.delete(key);
    }

    /**
     * true 不存在，放一个key
     * false 已存在
     * @param key
     * @param second
     * @return
     */
    public boolean validateRepeat(String key, Long second) {
        if(redisTemplate.hasKey(key)) {
            // key 已存在
            return false;
        } else {
            // key 不存在
            setObject(key, key, second);
            return true;
        }
    }
}
